#################################################################################
#     File Name           :     C:/Users/marshall_blundell/Dropbox/LucasGas/Code/spatial_analysis.R
#     Created By          :     
#     Creation Date       :     [2021-06-09 19:36]
#     Last Modified       :     [2021-06-14 16:23]
#     Description         :      
#################################################################################

#
# Preamble.
#
library(pacman)
p_load(tidyverse, sf, tigris, writexl)
# p_load(tictoc, furrr)

dropbox.dir <- "C:/Users/marshall_blundell/Dropbox/LucasGas/"

# 
# Load utilities shapefile
#
ious <- st_read(paste0(dropbox.dir, "OriginalData/Natural_Gas_Service_Territories/NG_Service_Terr.shp"))

# Change projection to albers
ious <- st_transform(ious, crs = 102003)

# Correct self intersection in some polygons
ious <- lwgeom::st_make_valid(ious)


# Function gets state data and intersects with cbgs for tigris shapefile for a given year
grab.cbgs.state.intersect <- function(tigris.year, tigris.state) {

    # Load cbgs and make sf object
    cbgs <- st_as_sf(tigris::block_groups(state = tigris.state, year = tigris.year, cb = F))

    # Transform to albers
    cbgs <- st_transform(cbgs, 102003)

    print(paste0("Loaded data for state ", tigris.state))

    # Make variable w area
    cbgs <- cbgs %>%
        mutate(cbg.area = as.numeric(st_area(.)))

    # run intersectoin and make weight
    cbgs.to.ious <- st_intersection(cbgs, ious) %>%
        mutate(cbg.area.weight = as.numeric(st_area(.)) / cbg.area) %>%
        select(GEOID, FID, SVCTERID, NAME, cbg.area.weight) %>%
        st_set_geometry(NULL)

    print(paste0("Completed merge for state ", tigris.state))

    return(cbgs.to.ious)
}

states <- unique(fips_codes$state_code)
states <- states[-which(states== "74")]

out.2000 <- map_dfr(states, function(x) grab.cbgs.state.intersect(2000, x)) 

out.2000 <- out.2000 %>%
    rename(cbg = BKGPIDFP00)

write_rds(out.2000, paste0(dropbox.dir, "ModifiedData/iou.cbg.crosswalk.year.2000.rds"))
write_xlsx(out.2000, paste0(dropbox.dir, "ModifiedData/iou_cbg_crosswalk_year_2000.xlsx"))

out.2019 <- map_dfr(states, function(x) grab.cbgs.state.intersect(2019, x)) 

write_rds(out.2019, paste0(dropbox.dir, "ModifiedData/iou.cbg.crosswalk.year.2019.rds"))
write_xlsx(out.2019, paste0(dropbox.dir, "ModifiedData/iou_cbg_crosswalk_year_2019.xlsx"))
